package it.tukano.collections;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * A key-list map
 * @author pgi
 * @param <K> the type of the keys
 * @param <V> the type of the list of values
 */
public class MapList<K, V> extends HashMap<K, List<V>> {

    private static final long serialVersionUID = 0;

    /**
     * Instance initializer
     */
    public MapList() {
    }

    /**
     * Returns the list for the given key or an empty list
     * @param key the key
     * @return the rquestes list or an empty list
     */
    public List<V> getOrEmpty(K key) {
        final List<V> list = get(key);
        return list == null ? Collections.<V>emptyList() : list;
    }

    /**
     * Returns the list mapped to the given key or a new empty mutable list
     * stored in the map for the same key
     * @param key the key
     * @return the stored list or a newly mapped one
     */
    public List<V> getOrCreate(K key) {
        List<V> list = get(key);
        if(list == null) put(key, list = new LinkedList<V>());
        return list;
    }

    /**
     * Append a value to the list at key. Creates the list if it has not been
     * added yet
     * @param key the key of the list of values
     * @param value the value to append
     */
    public void append(K key, V value) {
        List<V> list = get(key);
        if(list == null) put(key, list = new LinkedList<V>());
        list.add(value);
    }

    /**
     * Removes an element from the list at key
     * @param key the key of the list
     * @param value the value to remove
     */
    public void remove(K key, V value) {
        List<V> list = get(key);
        if(list != null) list.remove(value);
    }
}
